
import csv
import sys
import getopt
from tagger import COL
from elementtree.SimpleXMLWriter import XMLWriter
from datetime import datetime
import re
class config:
    skipHeader = True
    thres = 5 # 
    fmt = "%Y-%m-%dT%H:%M:%S.000"

class Line:
    timere = re.compile(r'(\d+)/(\d+)/(\d+)_(\d+):(\d+):(\d+)(\.(\d+))?')
    def __init__(self, row):
        self.time = Line.toTime(row[COL.time])
        #self.tag = row[COL.tag] 
        self.row = row
    def __str__(self):
        return str(self.row)
    @staticmethod    
    def toTime(str):
        r = Line.timere.match(str)
        if (r!=None):
            r = list(r.groups())
        else: 
            return datetime(1900,1,1)
        del r[6]
        tmp = []
        
        for x in r:
            if (x == None):
                tmp.append(0)
            else :
                tmp.append(int(x))
        r = tmp
        return datetime(r[0], r[1], r[2], r[3], r[4], r[5], r[6])


def plainOutput(line):
    global xml
    fmt = config.fmt
    row = line.row
    xml.start("event", start=line.time.strftime(fmt),
            title=row[COL.src] + "@" + row[COL.host] + "," + row[COL.action] + 
            ":" + row[COL.target])
    xml.data(row[COL.src] + "@" + row[COL.host] + '[' + row[COL.src] + 
             ']\n' + 'tamper:' + row[COL.tamper] + "\n" + 'misc:' + row[COL.misc])
    xml.end('event')
    
def toXML(rows,outputFile):
    global xml
    import codecs
    with open(outputFile,'w') as f:
        f = codecs.EncodedFile(f, 'ascii', 'utf8',errors='ignore')
        xml = XMLWriter(f)
        xml.start('data')
        for row in rows:
            plainOutput(Line(row))
        xml.end('data')

if (__name__ == '__main__'):
    from mainwindow import MainWindow
    from PyQt4.QtGui import *
    app = QApplication(sys.argv)
    w = MainWindow()
    w.readCSV('out.csv')
    toXML(w._data,'out.xml')
    
